package com.yx.changdao.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yx.changdao.common.annotation.AutoLog;
import com.yx.changdao.common.data.Pager;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.entity.DepContactGroup;
import com.yx.changdao.common.entity.DepWorker;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.utils.Faster;
import com.yx.changdao.common.utils.SysConst;
import com.yx.changdao.common.utils.SysUtils;
import com.yx.changdao.common.valid.Default;
import com.yx.changdao.common.valid.Update;
import com.yx.changdao.service.DepContactGroupService;
import com.yx.changdao.service.DepWorkerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 工作人员
 * <br/>
 *
 * @Auther: zcz
 * @create 2020/04/30 14:04
 */
@Validated
@RestController
@RequestMapping("dep/worker")
public class DepWorkerController {

    /**
     * 工作人员服务
     */
    @Autowired
    private DepWorkerService depWorkerService;
    /**
     * 联户人小组服务
     */
    @Autowired
    private DepContactGroupService depContactGroupService;

    /**
     * 列表
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/list")
//    @RequiresPermissions("dep:worker:list")
//    @ShiroDesc("工作人员:列表")
    public Result list(@RequestParam(value = "page") Long page,
                       @RequestParam(value = "limit", required = false) Integer limit,
                       @RequestParam(value = "contactGroupId") Long contactGroupId) throws AlertException {
        if (limit == null) {
            limit = SysConst.LIMIT_PAGE;
        }
        // 分页配置
        Page<DepWorker> pager = new Page<>(page, limit);
        // 根据请求解析条件。
        QueryWrapper<DepWorker> cnd = SysUtils.autoCnd(DepWorker.class);
        cnd.eq(DepWorker.CONTACT_GROUP_ID,contactGroupId);
        cnd.eq(DepWorker.DEP_ID,SysUtils.currentUser().getDepId());
        // 获取分页结果集。
        Page<DepWorker> dealPage = this.depWorkerService.page(pager, cnd);
        Map<String, Object> map = new HashMap<>();
        HashMap<String, String> hashMap = new HashMap<>();
        if (Faster.IsNotEmpty(dealPage.getRecords())){
            hashMap.put("depName",dealPage.getRecords().get(0).getDepName());
            hashMap.put("groupName",dealPage.getRecords().get(0).getGroupName());
        }
        map.put("name",hashMap);
        map.put("list", dealPage.getRecords());
        map.put("pager", new Pager(dealPage));
        return Result.ok().data(map);
    }

    /**
     * 添加/修改小组下的工作人员
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PostMapping
    public Result add(@RequestBody @Validated(Default.class) List<DepWorker>  depWorkers) throws AlertException {
        Faster.throwNull(depWorkers);
        DepContactGroup contactGroup = depContactGroupService.getOne(new QueryWrapper<DepContactGroup>().eq(DepContactGroup.CONTACT_GROUP_ID, depWorkers.get(0).getContactGroupId()));
        if (Faster.isNull(contactGroup)) {
            throw new AlertException("小组不存在");
        }
        if(depWorkers.size() > 3){
            throw new AlertException("一个小组下最多只能有三个工作人员");
        }
        // 同一部门下，不能有重名的
        /*if(depWorkers.size() == 2){
            if(depWorkers.get(0).getWorkerName().equals(depWorkers.get(1).getWorkerName())){
                throw new AlertException("人员名称不可重复");
            }
            if(depWorkers.get(0).getWorkerPhone().equals(depWorkers.get(1).getWorkerPhone())){
                throw new AlertException("手机号不可重复");
            }
        }*/
        List<String> workerName=new ArrayList<>();
        List<String> workerPhone=new ArrayList<>();
        for (DepWorker depWorker : depWorkers) {
            if(workerName.contains(depWorker.getWorkerName())){
                throw new AlertException("人员名称不可重复");
            }
            workerName.add(depWorker.getWorkerName());
            if(workerPhone.contains(depWorker.getWorkerPhone())){
                throw new AlertException("手机号不可重复");
            }
            workerPhone.add(depWorker.getWorkerPhone());
        }
        for (DepWorker depWorker:depWorkers){
            depWorker.setContactGroupId(depWorkers.get(0).getContactGroupId());
            depWorker.setDepId(SysUtils.currentUser().getDepId());
            depWorker.setDepName(SysUtils.currentUser().getDepName());
            depWorker.setGroupName(contactGroup.getGroupName());
            if(null != depWorker.getDepWorkerId() ){
                // 修改验证手机号
                int dwCount = depWorkerService.count(new QueryWrapper<DepWorker>().ne(DepWorker.DEP_WORKER_ID, depWorker.getDepWorkerId())
                        .eq(DepWorker.WORKER_PHONE,depWorker.getWorkerPhone()));
                if (0 < dwCount) {
                    throw new AlertException("手机号已存在");
                }
                depWorker.setUpdateBy(SysUtils.currentUserId());
                depWorker.setUpdateByName(SysUtils.currentUserName());
                depWorker.setUpdateTime(Faster.now());
            }else{
                // 新增验证手机号
                int dwCount = depWorkerService.count(new QueryWrapper<DepWorker>().eq(DepWorker.WORKER_PHONE,depWorker.getWorkerPhone()));
                if (0 < dwCount) {
                    throw new AlertException("手机号已存在");
                }
            }
        }
        boolean b = depWorkerService.saveOrUpdateBatch(depWorkers);
        if (!b) {
            throw new AlertException("操作失败");
        }
        return Result.ok("操作成功");
    }


    /**
     * 获得指定id下的工作人员
     *
     * @param
     * @return Result
     */
    @AutoLog
    @GetMapping("/{id}")
//    @RequiresPermissions("dep:worker:look")
//    @ShiroDesc("工作人员:查看")
    public Result get(@PathVariable("id") String id) throws AlertException {
        DepWorker depWorker = depWorkerService.getById(id);
        if (depWorker == null) {
            throw new AlertException("未找到相关人员信息");
        }
        return Result.ok().data(depWorker);
    }


    /**
     * 更新部门工作人员
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PutMapping
//    @RequiresPermissions("dep:worker:save")
//    @ShiroDesc("部门工作人员:保存")
    public Result update(@RequestBody @Validated(Update.class) DepWorker depWorker) throws AlertException {
        // 不可以修改小组
        depWorker.setContactGroupId(null);
        depWorker.setGroupName(null);
        boolean b = depWorkerService.updateById(depWorker);
        if (!b) {
            throw new AlertException("操作失败");
        }
        return Result.ok("操作成功");
    }


    /**
     * 删除部门工作人员
     *
     * @param
     * @return Result
     */
    @AutoLog
    @DeleteMapping("/{depWorkerId}")
//    @RequiresPermissions("dep:worker:del")
//    @ShiroDesc("部门工作人员:删除")
    public Result delete(@PathVariable("depWorkerId") String depWorkerId) throws AlertException {
        boolean b = depWorkerService.removeById(depWorkerId);
        if (!b) {
            throw new AlertException("删除失败");
        }
        return Result.ok("删除成功");
    }

}
